const {
  app,
  BrowserWindow,
  ipcMain,
  Menu,
  dialog,
  Notification,
} = require("electron");
const path = require("path");
const { setDefaultProtocol } = require("./plugins/protocol.js");

// 纯函数
const handleSetTitle = (event, title) => {
  const webContents = event.sender;
  const win = BrowserWindow.fromWebContents(webContents);
  win.setTitle(title);
};

async function handleFileOpen() {
  const { canceled, filePaths } = await dialog.showOpenDialog();
  if (canceled) {
    return;
  } else {
    return filePaths[0];
  }
}
function showNotification() {
  new Notification({
    title: NOTIFICATION_TITLE,
    body: NOTIFICATION_BODY,
  }).show();
}
// 纯函数
let win = null;
const createWindow = () => {
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
  });

  const menu = Menu.buildFromTemplate([
    {
      label: app.name,
      submenu: [
        {
          click: () => win.webContents.send("update-counter", 1),
          label: "Increment",
        },
        {
          click: () => win.webContents.send("update-counter", -1),
          label: "Decrement",
        },
      ],
    },
  ]);

  Menu.setApplicationMenu(menu);
  ipcMain.on("counter-value", (_event, value) => {
    console.log(value); // 将打印到 Node 控制台
  });

  win.loadFile("index.html");

  // Open the DevTools.
  // win.webContents.openDevTools();

  setDefaultProtocol();
};

const NOTIFICATION_TITLE = "Basic Notification";
const NOTIFICATION_BODY = "Notification from the Main process";

const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
  app.quit();
} else {
  app.on("second-instance", (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到myWindow这个窗口
    if (win) {
      if (win.isMinimized()) win.restore();
      win.focus();
    }
  });

  app
    .whenReady()
    .then(() => {
      ipcMain.on("set-title", handleSetTitle);
      createWindow();
      ipcMain.handle("dialog:openFile", handleFileOpen);

      app.on("activate", () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
      });
    })
    .then(showNotification);

  app.on("window-all-closed", () => {
    if (process.platform !== "darwin") app.quit();
  });
}

